package com.yupi.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.constant.CommonConstant;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.exception.ThrowUtils;
import com.yupi.oj.mapper.QuestionInfoMapper;
import com.yupi.oj.model.dto.questioninfo.QuestionInfoQueryRequest;
import com.yupi.oj.model.entity.QuestionInfo;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.vo.QuestionInfoVO;
import com.yupi.oj.model.vo.UserVO;
import com.yupi.oj.service.QuestionInfoService;
import com.yupi.oj.service.UserService;
import com.yupi.oj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 1
* @description 针对表【question_info(题目)】的数据库操作Service实现
* @createDate 2023-09-04 21:51:02
*/
@Service
public class QuestionInfoServiceImpl extends ServiceImpl<QuestionInfoMapper, QuestionInfo>
    implements QuestionInfoService{

    private final static Gson GSON = new Gson();

    @Resource
    private UserService userService;

    /**
     * todo 校验问题信息  需要重做
     * @param questionInfo
     * @param add
     */
    @Override
    public void validQuestionInfo(QuestionInfo questionInfo, boolean add) {
        if (questionInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = questionInfo.getTitle();
        String content = questionInfo.getContent();
        String tags = questionInfo.getTags();
        String answer = questionInfo.getAnswer();
        String judgeCase = questionInfo.getJudgeCase();
        String judgeConfig = questionInfo.getJudgeConfig();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags,answer,judgeCase,judgeConfig), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
        if (StringUtils.isNotBlank(tags) && tags.length() > 256) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签过长");
        }
        if (StringUtils.isNotBlank(answer) && answer.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "答案过长");
        }
        if (StringUtils.isNotBlank(judgeCase) && judgeCase.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "测试用例过长");
        }
        if (StringUtils.isNotBlank(judgeConfig) && judgeConfig.length() > 1024) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "测试配置过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param questionInfoQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionInfo> getQueryWrapper(QuestionInfoQueryRequest questionInfoQueryRequest) {
        QueryWrapper<QuestionInfo> queryWrapper = new QueryWrapper<>();
        if (questionInfoQueryRequest == null) {
            return queryWrapper;
        }
        String sortField = questionInfoQueryRequest.getSortField();
        String sortOrder = questionInfoQueryRequest.getSortOrder();
        Long id = questionInfoQueryRequest.getId();
        String title = questionInfoQueryRequest.getTitle();
        String content = questionInfoQueryRequest.getContent();
        List<String> tagList = questionInfoQueryRequest.getTags();
        Long userId = questionInfoQueryRequest.getUserId();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        if (CollectionUtils.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public QuestionInfoVO getQuestionInfoVO(QuestionInfo questionInfo, HttpServletRequest request) {
        QuestionInfoVO questionInfoVO = QuestionInfoVO.objToVo(questionInfo);
        long questionInfoId = questionInfo.getId();
        // 1. 关联查询用户信息
        Long userId = questionInfo.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionInfoVO.setUser(userVO);
        return questionInfoVO;
    }

    @Override
    public Page<QuestionInfoVO> getQuestionInfoVOPage(Page<QuestionInfo> questionInfoPage, HttpServletRequest request) {
        List<QuestionInfo> questionInfoList = questionInfoPage.getRecords();
        Page<QuestionInfoVO> questionInfoVOPage = new Page<>(questionInfoPage.getCurrent(), questionInfoPage.getSize(), questionInfoPage.getTotal());
        if (CollectionUtils.isEmpty(questionInfoList)) {
            return questionInfoVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionInfoList.stream().map(QuestionInfo::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        User loginUser = userService.getLoginUserPermitNull(request);
        // 填充信息
        List<QuestionInfoVO> questionInfoVOList = questionInfoList.stream().map(questionInfo -> {
            QuestionInfoVO questionInfoVO = QuestionInfoVO.objToVo(questionInfo);
            Long userId = questionInfo.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionInfoVO.setUser(userService.getUserVO(user));
            return questionInfoVO;
        }).collect(Collectors.toList());
        questionInfoVOPage.setRecords(questionInfoVOList);
        return questionInfoVOPage;
    }
}




